<template>
  <el-table :data="userData" style="width: 100%">
    <el-table-column label="序号" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="用户名" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span style="margin-left: 10px">{{ scope.row.username }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-popconfirm
          title="你确认要删除该用户吗?"
          confirm-button-text="确定"
          cancel-button-text="取消"
          @confirm="handleDelete(scope.$index, scope.row)"
        >
          <template #reference>
            <el-button size="small" type="danger"> 删除 </el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import axios from "axios";
const userData = ref([]);
function getUserList() {
  axios.get("http://localhost:3000/users").then((res) => {
    console.log(res.data);
    userData.value = res.data;
  });
}

function handleDelete(index, row) {
  axios.delete("http://localhost:3000/users/" + row.id).then((result) => {
    console.log(result);
    if (result.status === 200) {
      // 删除成功
      ElMessage({
        message: "删除成功！",
        type: "success",
      });
      getUserList();
    } else {
      // 删除失败
      ElMessage.error('删除失败，请检查网络连接！')
    }
  });
}

onMounted(() => {
  getUserList();
});
</script>

<style scoped>
</style>